<!DOCTYPE html>
<html lang="zh_cn">
<head>
          <title>来玩魔王的咚</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8" />
        <!-- twitter card metadata -->
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/mowang.png">
<meta name="twitter:site" content="">
<meta name="twitter:title" content="Go 网络编程示例">
<meta name="twitter:description" content="<p>并发时钟服务器：并发回声服务器；接收完回声再结束；聊天服务器；聊天服务器功能扩展</p>">
        <!-- OG Tags -->
<meta property="og:url" content="/gopl-pkg-net.html"/>
<meta property="og:title" content="来玩魔王的咚 | Go 网络编程示例" />
<meta property="og:description" content="<p>并发时钟服务器：并发回声服务器；接收完回声再结束；聊天服务器；聊天服务器功能扩展</p>" />
        <!-- favicon -->
        <link rel="icon" type="image/png" href="/images/mowang.png">
        <!-- moment.js for date formatting -->
        <script src="/theme/js/moment.js"></script>
        <!-- css -->
        <link rel="stylesheet" type="text/css" href="/theme/css/main.css" />
        <!-- 左边的menu，如果页面高度不够，就跟着滚动，否则文章分类显示不全 -->
        <link rel="stylesheet" type="text/css" href="/theme/css/mycss/menu.css" />
		<script>
			
                /*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
    
    (function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
                
                grunticon(["/theme/css/icons.data.svg.css", "/theme/css/icons.data.png.css", "/theme/css/icons.fallback.css"]);
            </script>
        <noscript><link href="/theme/css/icons.fallback.css" rel="stylesheet"></noscript>
        <!-- menu toggle javascript -->
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", initMenu);
            
            function initMenu(){
                var menu = document.getElementById("menu");
                var menulink = document.getElementById("menu-link");
                menulink.addEventListener("click", function toggleMenu(){
                        window.event.preventDefault();
                        menulink.classList.toggle('active');
                        menu.classList.toggle('active');              
                    });
            };
        </script>
        <!-- 不蒜子 -->
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    <meta name="description" content="<p>并发时钟服务器：并发回声服务器；接收完回声再结束；聊天服务器；聊天服务器功能扩展</p>" />

    <meta name="tags" content="gopl" />
  <!-- 替换部分base的样式，看文章时，要再宽一点，右边有很多空间可以撑开 -->
  <link rel="stylesheet" type="text/css" href="/theme/css/mycss/article.css" />

</head>
<body>
    <div role="banner" id="masthead">
        <header>
            <a href="/"><img src="/images/mowang.png" alt="McManus Logo"></a>
                <h1>来玩魔王的咚@骑士救兵</h1>
            <a href="#menu" id="menu-link">more stuff</a>
            <nav id="menu">
                <ul>
                        <li><a href="/tags">tags</a></li>
                            <li><a href="/category/cloud.html">Cloud</a></li>
                            <li><a href="/category/docker.html">Docker</a></li>
                            <li class="active"><a href="/category/go.html">Go</a></li>
                            <li><a href="/category/linux.html">Linux</a></li>
                            <li><a href="/category/python.html">Python</a></li>
                            <li><a href="/category/xue-xi-bi-ji.html">学习笔记</a></li>
                            <li><a href="/category/yun-wei-zi-dong-hua.html">运维自动化</a></li>
                </ul>
            </nav>
        </header>
    </div>
        <div class="page" role="main">
  <div class="article" role="article">
    <article>
        <footer>
            <a name="top"></a>
            <p>
              <time datetime=" 2020-08-06 15:30:00+08:00">
                <script>document.write(moment('2020-08-06 15:30:00+08:00').format('LL'));</script>
              </time>
              ~
              <time datetime=" 2020-08-06 15:30:00+08:00">
                <script>document.write(moment('2020-08-06 15:30:00+08:00').format('LL'));</script>
              </time>
            </p>
        </footer>
        <header>
          <h2>
            Go 网络编程示例
          </h2>
        </header>
      <div class="content">
         <div class="toc">
<ul>
<li><a href="#shi-li-bing-fa-shi-zhong-fu-wu-qi">示例：并发时钟服务器</a><ul>
<li><a href="#shi-zhong-fu-wu-qi">时钟服务器</a></li>
<li><a href="#ke-hu-duan-netcat">客户端 netcat</a></li>
<li><a href="#zhi-chi-bing-fa-de-fu-wu-qi">支持并发的服务器</a></li>
</ul>
</li>
<li><a href="#shi-li-bing-fa-hui-sheng-fu-wu-qi">示例：并发回声服务器</a><ul>
<li><a href="#you-qu-de-hui-sheng-fu-wu-duan">有趣的回声服务端</a></li>
<li><a href="#sheng-ji-ke-hu-duan">升级客户端</a></li>
<li><a href="#you-hua-fu-wu-duan">优化服务端</a></li>
<li><a href="#xiao-jie">小结</a></li>
</ul>
</li>
<li><a href="#jie-shou-wan-hui-sheng-zai-jie-shu">接收完回声再结束</a><ul>
<li><a href="#ke-hu-duan-you-hua">客户端优化</a></li>
<li><a href="#fu-wu-duan-you-hua">服务端优化</a></li>
<li><a href="#chao-shi-duan-kai">超时断开</a></li>
</ul>
</li>
<li><a href="#shi-li-liao-tian-fu-wu-qi">示例：聊天服务器</a><ul>
<li><a href="#zhu-han-shu">主函数</a></li>
<li><a href="#guang-bo-qi">广播器</a></li>
<li><a href="#ke-hu-duan-chu-li-han-shu">客户端处理函数</a></li>
<li><a href="#shi-yong-ke-hu-duan-jin-xing-liao-tian">使用客户端进行聊天</a></li>
</ul>
</li>
<li><a href="#liao-tian-fu-wu-qi-gong-neng-kuo-zhan">聊天服务器功能扩展</a><ul>
<li><a href="#tong-zhi-dang-qian-de-yong-hu-lie-biao">通知当前的用户列表</a></li>
<li><a href="#duan-diao-zhang-shi-jian-kong-xian-de-ke-hu-duan">断掉长时间空闲的客户端</a></li>
<li><a href="#ke-hu-duan-ke-yi-shu-ru-ming-zi">客户端可以输入名字</a></li>
<li><a href="#yu-fang-ke-hu-duan-yan-chi-ying-xiang">预防客户端延迟影响</a></li>
<li><a href="#wan-zheng-dai-ma">完整代码</a></li>
</ul>
</li>
</ul>
</div>
<h3 id="shi-li-bing-fa-shi-zhong-fu-wu-qi"><a class="toclink" href="#shi-li-bing-fa-shi-zhong-fu-wu-qi">示例：并发时钟服务器</a></h3>
<p>本节介绍 net 包，它提供构建客户端和服务器程序的组件，这些程序通过 TCP、UDP 或者 UNIX 套接字进行通信。网络服务 net/http 包是在 net 包的基础上构建的。  </p>
<h4 id="shi-zhong-fu-wu-qi"><a class="toclink" href="#shi-zhong-fu-wu-qi">时钟服务器</a></h4>
<p>这个示例是一个时钟服务器，它以每秒一次的频率向客户端发送当前时间：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;time&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;localhost:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"> </span><span class="c1">// 例如，连接终止</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 一次处理一个连接</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">WriteString</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Now</span><span class="p">().</span><span class="nx">Format</span><span class="p">(</span><span class="s">&quot;2006/01/02 15:04:05\r\n&quot;</span><span class="p">))</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">return</span><span class="w"> </span><span class="c1">// 例如，连接断开</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="mi">1</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>Listen 函数创建一个 net.Listener 对象，它在一个网络端口上监听进来的连接，这里是 TCP 端口 localhost:8000。监听器的 Accept 方法被阻塞，知道有连接请求进来，然后返回 net.Conn 对象来代表一个连接。<br>
handleConn 函数处理一个完整的客户端连接。在循环里，它将 time.Now() 获取的当前时间发送给客户端。因为 net.Conn 满足 io.Writer 接口，所以可以直接向它进行写入。当写入失败时循环结束，很多时候是客户端断开连接，这是 handleConn 函数使用延迟（defer）的 Close 调用关闭自己这边的连接，然后继续等待下一个连接请求。  </p>
<p>为了连接到服务器，还需要一个 socket 客户端，这里可以先使用系统的 telnet 来进行验证：</p>
<div class="highlight"><pre><span></span><code>$ telnet localhost <span class="m">8000</span>
</code></pre></div>

<p>这里可以开两个 telnet 尝试进行连接，只有第一个可以连接上，而其他的连接会阻塞。当把第一个客户端的连接断开后，服务端会重新返回到 main 函数的 for 循环中等待新的连接。此时之前阻塞的一个连接就能连接进来，继续显示时间。服务端程序暂时先这样，先来实现一个 socket 客户端程序。  </p>
<h4 id="ke-hu-duan-netcat"><a class="toclink" href="#ke-hu-duan-netcat">客户端 netcat</a></h4>
<p>下面的客户端使用 net.Dial 实现了 Go 版本的 netcat 程序，用来连接 TCP服务器：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;os&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Dial</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;localhost:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdout</span><span class="p">,</span><span class="w"> </span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">dst</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Writer</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Reader</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">dst</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="p">);</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这个程序从网络连接中读取，然后写到标准输出，直到到达 EOF 或者出错。  </p>
<h4 id="zhi-chi-bing-fa-de-fu-wu-qi"><a class="toclink" href="#zhi-chi-bing-fa-de-fu-wu-qi">支持并发的服务器</a></h4>
<p>如果打开多个客户端，同时只有一个客户端能正常工作。第二个客户端必须等到第一个结束才能正常工作，这是因为服务器是<strong>顺序</strong>的，一次只能处理一个客户请求。让服务器支持并发只需要一个很小的改变：在调用 handleConn 的地方添加一个 <strong>go</strong> 关键字，使它在自己的 goroutine 内执行。<br>
代码如下：</p>
<div class="highlight"><pre><span></span><code><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"> </span><span class="c1">// 例如，连接终止</span><span class="w"></span>
<span class="w">        </span><span class="k">continue</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 并发处理连接</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>现在的版本，多个客户端可以同时接入并正常工作了。  </p>
<h3 id="shi-li-bing-fa-hui-sheng-fu-wu-qi"><a class="toclink" href="#shi-li-bing-fa-hui-sheng-fu-wu-qi">示例：并发回声服务器</a></h3>
<p>上面的时钟服务器每个连接使用一个 goroutine。下面要实现的这个回声服务器，每个连接使用多个 goroutine 来处理。大多数的回声服务器仅仅将读到的内容写回去。<br>
所以可以使用下面简单的 handleConn 版本：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="you-qu-de-hui-sheng-fu-wu-duan"><a class="toclink" href="#you-qu-de-hui-sheng-fu-wu-duan">有趣的回声服务端</a></h4>
<p>下面的这个版本可以重复3次，第一个全大写，第二次正常，第三次全小写：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// reverb1</span><span class="w"></span>
<span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;bufio&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;fmt&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;strings&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;time&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="nx">delay</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Duration</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToUpper</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToLower</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">(),</span><span class="w"> </span><span class="mi">1</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 注意：忽略 input.Err() 中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn0</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;localhost:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"> </span><span class="c1">// 例如，连接终止</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 并发处理连接</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>在上一个示例中，已经知道需要使用 go 关键字调用 handleConn 函数。不过在这个例子中，重点不是处理多个客户端的连接，所以这里不是重点。  </p>
<h4 id="sheng-ji-ke-hu-duan"><a class="toclink" href="#sheng-ji-ke-hu-duan">升级客户端</a></h4>
<p>现在来升级一下客户端，使它可以在终端上向服务器输入，还可以将服务器的回复复制到输出。<br>
这里提供了另一个使用并发的机会：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;os&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">dst</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Writer</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Reader</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">dst</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="p">);</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Dial</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdout</span><span class="p">,</span><span class="w"> </span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdin</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="you-hua-fu-wu-duan"><a class="toclink" href="#you-hua-fu-wu-duan">优化服务端</a></h4>
<p>使用上面的服务端版本，如果有多个连续的输入，新输入的内容不会马上返回，而是要等待之前输入的内容全部返回后才会处理之后的内容。要想做的更好，需要更多的 goroutine。<br>
再一次，在调用 echo 时需要加入 go 关键字：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// reverb2</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">(),</span><span class="w"> </span><span class="mi">1</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 注意：忽略 input.Err() 中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这个改进的版本，回声也是并发的，在时间上互相重合。  </p>
<h4 id="xiao-jie"><a class="toclink" href="#xiao-jie">小结</a></h4>
<p>这就是使服务器变成并发所要做的，不仅处理来自多个客户端的链接，还包括在一个连接处理中，使用多个 go 关键字。在这个例子里，单个客户端连接也可以同时发起多个请求。在最初的版本里，没有使用 go 调用 echo，所以处理单个客户端的请求不是并发的，只有前一个处理完才会继续处理下一个。之后改进的版本，使用 go 调用 echo，这里对每一个请求的处理都是并发的了。<br>
然而，在添加这些 go 关键字的同时，必须要仔细考虑方法 net.Conn 的并发调用是不是安全的，对大多数类型来讲，这都是不安全的。  </p>
<h3 id="jie-shou-wan-hui-sheng-zai-jie-shu"><a class="toclink" href="#jie-shou-wan-hui-sheng-zai-jie-shu">接收完回声再结束</a></h3>
<p>之前的客户端在主 goroutine 中将输入复制到服务器中，这样的客户端在输入接收后立即退出，即使后台的 goroutine 还在继续。<br>
为了让程序等待后台的 goroutine 在完成后再退出，使用一个通道来同步两个 goroutine：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Dial</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">done</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdout</span><span class="p">,</span><span class="w"> </span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意：忽略错误</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;done&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"> </span><span class="c1">// 通知主 goroutine 的信号</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>
<span class="w">    </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdin</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="o">&lt;-</span><span class="nx">done</span><span class="w"> </span><span class="c1">// 等待后台 goroutine 完成</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>当用户关闭标准输入流（Windows系统使用Ctrl+Z）时，mustCopy 返回，主 goroutine 调用 conn.Close() 来关闭两端网络连接。关闭写半边的连接会导致服务器看到 EOF。关闭读半边的连接导致后台 goroutine 调用 io.Copy 返回 “read from closed connection” 错误，所以这个版本里去掉了打印错误日志。  </p>
<h4 id="ke-hu-duan-you-hua"><a class="toclink" href="#ke-hu-duan-you-hua">客户端优化</a></h4>
<p>上面这个版本使用起来的效果和之前的版本并没有太大的差别，几乎看不到差别。虽然多了等待连接关闭，但是依然不会等待接收完毕所有服务器的返回。不过这步解决了等待 goroutine 运行完毕后，主 goroutine 才会结束。使用下面的 TCP 链接，就可以实现接收完毕所有信息后，goroutine 才会结束。<br>
在 net 包中，conn 接口有一个具体的类型 *net.TCPConn，它代表一个 TCP 连接：</p>
<div class="highlight"><pre><span></span><code><span class="nx">tcpAddr</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">ResolveTCPAddr</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
<span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">DialTCP</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">tcpAddr</span><span class="p">)</span><span class="w"></span>
<span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>TCP 链接由两半边组成，可以通过 CloseRead 和 CloseWrite 方法分别关闭。修改主 goroutine，仅仅关闭连接的写半边，这样程序可以继续执行输出来自 reverb1 服务器的回声，即使标准输入已经关闭。<br>
具体实现如下：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;os&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">tcpAddr</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">ResolveTCPAddr</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">DialTCP</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">tcpAddr</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">done</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdout</span><span class="p">,</span><span class="w"> </span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意：忽略错误</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;done&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"> </span><span class="c1">// 通知主 goroutine 的信号</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>
<span class="w">    </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdin</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">.</span><span class="nx">CloseWrite</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="o">&lt;-</span><span class="nx">done</span><span class="w"> </span><span class="c1">// 等待后台 goroutine 完成</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">dst</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Writer</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Reader</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">dst</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="p">);</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>现在只对第一个回声服务器版本 reverb1 有效，对于之后改进的可以并发处理同一个客户端多个请求的 reverb2 服务器，服务端还需要做一些修改。  </p>
<h4 id="fu-wu-duan-you-hua"><a class="toclink" href="#fu-wu-duan-you-hua">服务端优化</a></h4>
<p>在 reverb2 服务器的版本中，因为对于每一个连接，每一次回声的请求都会生成一个新的 goroutine 进行处理。为了知道什么时候最后一个 goroutine 结束（有时候不一定是最后启动的那个），需要在每一个 goroutine 启动千递增计数，在每一个 goroutine 结束时递减计数。这需要一个特殊设计的计数器，它可以被多个 goroutine 安全地操作，然后又一个方法一直等到他变为 0。这个计数器类型是 sync.WaitGroup。<br>
下面是完整的服务器代码：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;bufio&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;fmt&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;strings&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;sync&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;time&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">wg</span><span class="w"> </span><span class="nx">sync</span><span class="p">.</span><span class="nx">WaitGroup</span><span class="w"> </span><span class="c1">// 工作 goroutine 的个数</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="nx">delay</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Duration</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Done</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToUpper</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToLower</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Add</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">(),</span><span class="w"> </span><span class="mi">2</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 注意：忽略 input.Err() 中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Wait</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;localhost:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"> </span><span class="c1">// 例如，连接终止</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 并发处理连接</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>注意 Add 和 Done 方法的不对称性。Add 递增计数器，它必须工作在 goroutine 开始之前执行，而不是在中间。另外，Add 有一个参数，但 Done 没有，它等价于 Add(-1)。使用 defer 来确保计数器在任何情况下都可以递减。在不知道迭代次数的情况下，上面的代码结构是通用的，符合习惯的并行循环模式。  </p>
<h4 id="chao-shi-duan-kai"><a class="toclink" href="#chao-shi-duan-kai">超时断开</a></h4>
<p>下面的版本增加了超时断开的功能。这样服务端和客户端就各有两个断开连接的情况了，原本只有一种。<br>
这里需要用到 select 多路复用。  </p>
<h5 id="fu-wu-duan"><a class="toclink" href="#fu-wu-duan">服务端</a></h5>
<p>原本只要被动等待客户端断开就可以了，这个逻辑原本放在主 goroutine 中。现在服务端超时需要主动断开，客户端断开了，需要被动断开，这2个逻辑都需要一个单独的 goroutine，而主 goroutine 则阻塞接收这两个情况的通道。<br>
这样，任意一个通道有数据，就会断开并退出：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;bufio&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;fmt&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;strings&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;sync&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;time&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">wg</span><span class="w"> </span><span class="nx">sync</span><span class="p">.</span><span class="nx">WaitGroup</span><span class="w"> </span><span class="c1">// 工作 goroutine 的个数</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="nx">delay</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Duration</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Done</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToUpper</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">shout</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">time</span><span class="p">.</span><span class="nx">Sleep</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\t&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">ToLower</span><span class="p">(</span><span class="nx">shout</span><span class="p">))</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">c</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">stop1</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="nx">stop2</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>

<span class="w">    </span><span class="nx">inputSignal</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"> </span><span class="c1">// 有任何输入，就发送一个信号</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 接收客户端发送回声的goroutine</span><span class="w"></span>
<span class="w">        </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">c</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 注意：忽略 input.Err() 中可能的错误</span><span class="w"></span>
<span class="w">            </span><span class="nx">inputSignal</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">            </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Add</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">go</span><span class="w"> </span><span class="nx">echo</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">(),</span><span class="w"> </span><span class="mi">1</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="c1">// 退出上面的for循环，表示客户端断开</span><span class="w"></span>
<span class="w">        </span><span class="nx">stop1</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="nx">delay</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="w"></span>
<span class="w">    </span><span class="nx">timer</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">NewTimer</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 计算超时的goroutine</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">inputSignal</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="nx">timer</span><span class="p">.</span><span class="nx">Reset</span><span class="p">(</span><span class="nx">delay</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">timer</span><span class="p">.</span><span class="nx">C</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="c1">// 超时，断开连接</span><span class="w"></span>
<span class="w">                </span><span class="nx">stop2</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">stop1</span><span class="p">:</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">stop2</span><span class="p">:</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">wg</span><span class="p">.</span><span class="nx">Wait</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">c</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;localhost:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"> </span><span class="c1">// 例如，连接终止</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 并发处理连接</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h6 id="ke-hu-duan"><a class="toclink" href="#ke-hu-duan">客户端</a></h6>
<p>原本只需要响应接收标准输入的 Ctrl+Z 然后断开写半边的连接，这个逻辑也需要从主 goroutine 放到一个新的 goroutine 中。另外一种断开的连接是被动响应服务端的断开连接然后客户端也退出。这里还要稍微在复杂一点，如果是服务端的超时断开，则直接断开。如果是客户端的主动断开，则还需要继续等待服务端的断开，然后再退出。<br>
下面是客户端的代码：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;io&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;os&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">tcpAddr</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">ResolveTCPAddr</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">DialTCP</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">tcpAddr</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>

<span class="w">    </span><span class="nx">done1</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 打印回声的goroutine</span><span class="w"></span>
<span class="w">        </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdout</span><span class="p">,</span><span class="w"> </span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意：忽略错误</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;done&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">done1</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"> </span><span class="c1">// 通知主 goroutine 的信号</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="nx">done2</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 发送请求的goroutine</span><span class="w"></span>
<span class="w">        </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">os</span><span class="p">.</span><span class="nx">Stdin</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">.</span><span class="nx">CloseWrite</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="nx">done2</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 等待后台 goroutine 完成</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">done1</span><span class="p">:</span><span class="w"></span>
<span class="w">    </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">done2</span><span class="p">:</span><span class="w"> </span><span class="c1">// 客户端主动断开后，只关闭写半边连接</span><span class="w"></span>
<span class="w">        </span><span class="o">&lt;-</span><span class="nx">done1</span><span class="w"> </span><span class="c1">// 继续等待服务端断开，就是等待全是打印完毕</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">mustCopy</span><span class="p">(</span><span class="nx">dst</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Writer</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Reader</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nx">Copy</span><span class="p">(</span><span class="nx">dst</span><span class="p">,</span><span class="w"> </span><span class="nx">src</span><span class="p">);</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h3 id="shi-li-liao-tian-fu-wu-qi"><a class="toclink" href="#shi-li-liao-tian-fu-wu-qi">示例：聊天服务器</a></h3>
<p>实现一个聊天服务器，它可以在几个用户之间相互广播文本消息。<br>
这个程序中有四种 goroutine：</p>
<ul>
<li>主 goroutine，就是 main 函数</li>
<li>广播（broadcaster）goroutine。非常好的展示了 select 用法，因为它需要处理三种不同类型的消息</li>
<li>每一个连接里有一个连接处理（handleConn）goroutine </li>
<li>每一个连接里还有一个客户写入（clientWriter）goroutine</li>
</ul>
<h4 id="zhu-han-shu"><a class="toclink" href="#zhu-han-shu">主函数</a></h4>
<p>主函数的工作是监听端口，接受连接请求。对每一个连接，它创建一个新的 handleConn。<br>
就像之前的并发回声服务器中那样：</p>
<div class="highlight"><pre><span></span><code><span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="guang-bo-qi"><a class="toclink" href="#guang-bo-qi">广播器</a></h4>
<p>广播器，它的变量 clients 会记录当前连接的客户集合。<br>
其记录的内容是每一个客户端对外发送消息的通道：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 广播器</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">client</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="c1">// 对外发送消息的通道</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">client</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">leaving</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">client</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有接受的客户消息</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">clients</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="nx">client</span><span class="p">]</span><span class="kt">bool</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有连接的客户端集合</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">messages</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 把所有接收的消息广播给所有的客户</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 发送消息通道</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cli</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">msg</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">entering</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nx">clients</span><span class="p">[</span><span class="nx">cli</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">leaving</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nb">delete</span><span class="p">(</span><span class="nx">clients</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="nb">close</span><span class="p">(</span><span class="nx">cli</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>广播器监听两个全局的通道 entering 和 leaving。通过它们通知有客户进入和离开，如果从一个通道中接收到事件，它将更新 clients 集合。如果是客户离开，还会关闭对应客户对外发送消息的通道。<br>
广播器还监听 messages 通道，所有的客户都会将要广播的消息发送到这个通道。当收到一个消息后，就会把消息广播给所有客户。  </p>
<h4 id="ke-hu-duan-chu-li-han-shu"><a class="toclink" href="#ke-hu-duan-chu-li-han-shu">客户端处理函数</a></h4>
<p>handleConn 函数创建一个对外发送消息的新通道，然后通过 entering 通道通知广播器新客户进入。接着，要读取客户发来的每一条消息，通过 messages 通道将每一条消息发送给广播器，发送时再每条消息前面加上发送者的ID作为前缀。<br>
一旦客户端将消息读取完毕，handleConn 通过 leaving 通道通知客户离开，然后关闭连接：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数: handleConn</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 对外发送客户消息的通道</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="nx">who</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">RemoteAddr</span><span class="p">().</span><span class="nx">String</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">who</span><span class="w">           </span><span class="c1">// 这条单发给自己</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has arrived&quot;</span><span class="w"> </span><span class="c1">// 这条进行进行广播，但是自己还没加到广播列表中</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">ch</span><span class="w">                   </span><span class="c1">// 然后把自己加到广播列表中</span><span class="w"></span>

<span class="w">    </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot;: &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 注意，忽略input.Err()中可能的错误</span><span class="w"></span>

<span class="w">    </span><span class="nx">leaving</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">ch</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has left&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>另外，handleConn 函数还为每一个客户创建了写入（clientWriter）goroutine，每个客户都从自己的通道中接收消息发送给客户端的网络连接。<br>
在广播器收到 leaving 通知并关闭这个接收消息的通道后，clientWriter 会结束通道的遍历后运行结束：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数: clientWriter</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">ch</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="c1">// 在消息结尾使用 \r\n ，提升平台兼容</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintf</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;%s\r\n&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">msg</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意，忽略网络层面的错误</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>给客户端发送的消息字符串需要用"\n"结尾。如果换成"\r\n"结尾，平台的兼容性应该会更好。至少windows上的telnet客户端可以直接使用了。 </p>
<h4 id="shi-yong-ke-hu-duan-jin-xing-liao-tian"><a class="toclink" href="#shi-yong-ke-hu-duan-jin-xing-liao-tian">使用客户端进行聊天</a></h4>
<p>完整的源码就是上面的四段代码，拼在一起就能运行了。<br>
和之前使用回声服务器一样，可以用 telnet 或者也可以用之前写的 netcat 作为客户端来聊天。<br>
当有 n 个客户 session 在连接的时候，程序并发运行着 2n+2 个相互通信的 goroutine，它不需要隐式的加锁操作也能做到并发安全。clients map 被限制在广播器这一个 goroutine 中，所以不会被并发的访问。唯一被多个 goroutine 共享的变量是通道以及 net.Conn 的实例，它们也都是并发安全的。  </p>
<h3 id="liao-tian-fu-wu-qi-gong-neng-kuo-zhan"><a class="toclink" href="#liao-tian-fu-wu-qi-gong-neng-kuo-zhan">聊天服务器功能扩展</a></h3>
<p>上面的聊天服务器提供了一个很好的架构，现在再在其之上扩展功能就很方便了。  </p>
<h4 id="tong-zhi-dang-qian-de-yong-hu-lie-biao"><a class="toclink" href="#tong-zhi-dang-qian-de-yong-hu-lie-biao">通知当前的用户列表</a></h4>
<p>在新用户到来之后，告知该新用户当前在聊天室的所有的用户列表。每个用户加入后，系统都会自动生成一个用户名（基于用户的网络连接，之后会添加设置用户名的功能），就是要把这些存在的用户名打印出来。<br>
所有的用户列表只在广播器的 clients map 中，但是这个 map 又不包括用户名。<br>
所以先要修改数据类型，把每个连接的数据结构加上一个新的用户名字段：</p>
<div class="highlight"><pre><span></span><code><span class="kd">type</span><span class="w"> </span><span class="nx">client</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="c1">// 对外发送消息的通道</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">clientInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="nx">client</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>原本使用 client 作为元素的通道和 map，现在全部也都要换成 clientInfo 作为元素。<br>
向新用户发送当前用户列表的任务也在广播器中完成：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 广播器</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">client</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="c1">// 对外发送消息的通道</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">clientInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="nx">client</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">leaving</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有接受的客户消息</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">clients</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="nx">clientInfo</span><span class="p">]</span><span class="kt">bool</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有连接的客户端集合</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">messages</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 把所有接收的消息广播给所有的客户</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 发送消息通道</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cli</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">msg</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">entering</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 在每一个新用户到来的时候，通知当前存在的用户</span><span class="w"></span>
<span class="w">            </span><span class="kd">var</span><span class="w"> </span><span class="nx">users</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">users</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">append</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="p">.</span><span class="nx">name</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">users</span><span class="p">)</span><span class="w"> </span><span class="p">&gt;</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cli</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Sprintf</span><span class="p">(</span><span class="s">&quot;Other users in room: %s&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">Join</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;; &quot;</span><span class="p">))</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cli</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are the only user in this room.&quot;</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>

<span class="w">            </span><span class="nx">clients</span><span class="p">[</span><span class="nx">cli</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">leaving</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nb">delete</span><span class="p">(</span><span class="nx">clients</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="nb">close</span><span class="p">(</span><span class="nx">cli</span><span class="p">.</span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>客户端处理函数还需要做少量的修改，主要是因为数据结构变了。原本给 entering 和 leaving 通道发送的是 ch。现在要发送封装好 who 的结构体。<br>
客户端处理函数的代码略，之后的扩展中会贴出来：</p>
<div class="highlight"><pre><span></span><code><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">{</span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">}</span><span class="w"></span>
<span class="nx">entering</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">cli</span><span class="w"></span>
</code></pre></div>

<h4 id="duan-diao-zhang-shi-jian-kong-xian-de-ke-hu-duan"><a class="toclink" href="#duan-diao-zhang-shi-jian-kong-xian-de-ke-hu-duan">断掉长时间空闲的客户端</a></h4>
<p>如果在一段时间里，客户端没有任何输入，服务器就将客户端断开。之前的逻辑是，客户端处理函数会一直在阻塞在 input.Scan() 这里等待客户端输入。只要在另外一个 goroutine 中调用 conn.Close()，就可以让当前阻塞的读操作变成非阻塞，就像 input.Scan() 输入完成的读操作一样。不过这么做的话会有一点小问题，原本在主 goroutine 的结尾有一个<code>conn.Close()</code>操作，现在在定时的 goroutine 中还需要有一个关闭的操作。如果因为定时而结束的，就会有两次关闭操作。<br>
这里关闭的是 socket 连接，本质上就是文件句柄。尝试多次关闭貌似不会有什么问题，不过要解决这个问题也不难。一种是把响应用户输入的操作也放到 goroutine 中。现有有两个 goroutine 在运行，主 goroutine 则只要一直阻塞，通过一个通道等待其中任何一个 goroutine 完成后发送的信号即可。这样关闭的操作只在主 goroutine 中操作。<br>
下面的是客户端处理函数，包括上一个功能里修改的部分：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数: handleConn</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 对外发送客户消息的通道</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="nx">who</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">RemoteAddr</span><span class="p">().</span><span class="nx">String</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">{</span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">}</span><span class="w">       </span><span class="c1">// 打包好用户名和通道</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">who</span><span class="w">           </span><span class="c1">// 这条单发给自己</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has arrived&quot;</span><span class="w"> </span><span class="c1">// 这条进行进行广播，但是自己还没加到广播列表中</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">cli</span><span class="w">                  </span><span class="c1">// 然后把自己加到广播列表中</span><span class="w"></span>

<span class="w">    </span><span class="nx">done</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{},</span><span class="w"> </span><span class="mi">2</span><span class="p">)</span><span class="w"> </span><span class="c1">// 等待下面两个 goroutine 其中一个执行完成。使用缓冲通道防止 goroutine 泄漏</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 计算超时的goroutine</span><span class="w"></span>
<span class="w">    </span><span class="nx">inputSignal</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"> </span><span class="c1">// 有任何输入，就发送一个信号</span><span class="w"></span>
<span class="w">    </span><span class="nx">timeout</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">15</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="w">        </span><span class="c1">// 客户端空闲的超时时间</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">timer</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">NewTimer</span><span class="p">(</span><span class="nx">timeout</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">inputSignal</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="nx">timer</span><span class="p">.</span><span class="nx">Reset</span><span class="p">(</span><span class="nx">timeout</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">timer</span><span class="p">.</span><span class="nx">C</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="c1">// 超时，断开连接</span><span class="w"></span>
<span class="w">                </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">inputSignal</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">strings</span><span class="p">.</span><span class="nx">TrimSpace</span><span class="p">(</span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()))</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 禁止发送纯空白字符</span><span class="w"></span>
<span class="w">                </span><span class="k">continue</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot;: &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="c1">// 注意，忽略input.Err()中可能的错误</span><span class="w"></span>
<span class="w">        </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="o">&lt;-</span><span class="nx">done</span><span class="w"></span>
<span class="w">    </span><span class="nx">leaving</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">cli</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has left&quot;</span><span class="w"></span>
<span class="w">    </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这里还简单加了一个限制客户端发送空消息的功能，在 input.Scan() 循环中。空消息不会发送广播，但是可以重置定时器的时间。  </p>
<h4 id="ke-hu-duan-ke-yi-shu-ru-ming-zi"><a class="toclink" href="#ke-hu-duan-ke-yi-shu-ru-ming-zi">客户端可以输入名字</a></h4>
<p>在客户端连接后，不立刻进入聊天室，而是先输入一个名字。考虑到名字不能和已有的名字重复，而现有的名字都保存在广播器里的 clients 这个 map 中。所以客户端输入的名字需要在 clients 中查找一下是否已经有人用了。现在有了按名字进行查找的需求，clients 类型更适合使用一个以名字为 key 的 map 而不是原本的集合。<br>
这个 map 的 value 就是向该客户发送消息的通道，也就是最初这个集合的 key 的值：</p>
<div class="highlight"><pre><span></span><code><span class="nx">clients</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="nx">client</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有连接的客户端集合</span><span class="w"></span>
</code></pre></div>

<h5 id="ke-hu-duan-chu-li-han-shu_1"><a class="toclink" href="#ke-hu-duan-chu-li-han-shu_1">客户端处理函数</a></h5>
<p>在客户端处理函数的开头，需要增加注册用户名的过程。<br>
用户名注册的处理过程比较复杂，所以单独封装到了一个函数 clientRegiste 中：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">who</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientRegiste</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 新增这一行，注册获取用户名</span><span class="w"></span>

<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 对外发送客户消息的通道</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="c1">// who := conn.RemoteAddr().String() // 去掉这一行</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 之后的代码不变</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这里使用一个交互的方式来获取用户名，代替原本通过连接的信息自动生成。这个函数是串行的，只有在返回用户名后，才会继续执行下去。之后的代码和之前是一样的。<br>
在 clientRegiste 函数中，不停的和终端进行交互，处理收到的消息，如果用户名可用，继续执行之后的流程。<br>
如果用户名不可用，则提示用户继续处理：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数 clientRegiste</span><span class="w"></span>
<span class="c1">// 注册用户名</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">clientRegiste</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nx">who</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">bool</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprint</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;input nickname: &quot;</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意，忽略网络层面的错误</span><span class="w"></span>
<span class="w">    </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">strings</span><span class="p">.</span><span class="nx">TrimSpace</span><span class="p">(</span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()))</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 禁止发送纯空白字符</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">who</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="nx">register</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">registeInfo</span><span class="p">{</span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">ch</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">break</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintf</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;name %q is existed\r\ntry other name: &quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">who</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 注意，忽略input.Err()中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="nx">who</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>这里只有最简单的功能，还可以增加输入超时，以及尝试次数的限制。所以把这个函数独立出来完成功能，更方便之后对注册函数进行扩展。<br>
函数的主要逻辑就是 input.Scan() 的循环，这和 handleConn 中的循环十分相似。如果之后再加上输入超时，这两段的处理逻辑只有极小部分的差别，所以这部分代码也可以单独写一个函数。这里避免过早的优化，暂时就先这样，看着也比较清晰。之后要添加超时功能的时候，再把这部分重复的代码独立出来。<em>这部分优化最后完整的代码里会有。</em>  </p>
<h5 id="guang-bo-qi_1"><a class="toclink" href="#guang-bo-qi_1">广播器</a></h5>
<p>在广播器的 select 里要加一个分支，用来处理用户名的请求。收到请求后，判断是否已经存在，把结果返回给 clientRegiste。因为 clients 是只有广播器可见的，所以这里要使用通道传递过来，判断后再用通道把结果传回去。这样可以保证 clients 变量只在这一个 goroutine 里被使用（包括修改）。另外，每个客户端的注册都使用一个通道将注册信息发送给广播器，但是广播器返回的内容，需要对每个客户端使用不同的通道。<br>
所以这里，广播器新创建了专门用于注册交互的数据结构：</p>
<div class="highlight"><pre><span></span><code><span class="kd">type</span><span class="w"> </span><span class="nx">registeInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">bool</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">register</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">registeInfo</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注册用户名的通道</span><span class="w"></span>
</code></pre></div>

<p>客户注册的函数创建一个布尔型的通道，加上用户的名字封装到 registeInfo 结构体中。然后广播器判断后，把结果通道 registeInfo 里的 ch 字段这个通道，把结果返回给对应的客户注册函数。<br>
下面是广播器 broadcaster 的代码，主要是 select 新增了一个分支，处理注册用户名：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 广播器</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">client</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="c1">// 对外发送消息的通道</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">clientInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="nx">client</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">leaving</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有接受的客户消息</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">type</span><span class="w"> </span><span class="nx">registeInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">bool</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">register</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">registeInfo</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注册用户名的通道</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">clients</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="nx">client</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有连接的客户端集合</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">messages</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 把所有接收的消息广播给所有的客户</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 发送消息通道</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cli</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">msg</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">user</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">register</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 先判断新用户名是否有重复</span><span class="w"></span>
<span class="w">            </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clients</span><span class="p">[</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="p">]</span><span class="w"></span>
<span class="w">            </span><span class="nx">user</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="p">!</span><span class="nx">ok</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cliSt</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">entering</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 在每一个新用户到来的时候，通知当前存在的用户</span><span class="w"></span>
<span class="w">            </span><span class="kd">var</span><span class="w"> </span><span class="nx">users</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">user</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">users</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">append</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="nx">user</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">users</span><span class="p">)</span><span class="w"> </span><span class="p">&gt;</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Sprintf</span><span class="p">(</span><span class="s">&quot;Other users in room: %s&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">Join</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;; &quot;</span><span class="p">))</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are the only user in this room.&quot;</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>

<span class="w">            </span><span class="nx">clients</span><span class="p">[</span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">name</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cliSt</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">leaving</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nb">delete</span><span class="p">(</span><span class="nx">clients</span><span class="p">,</span><span class="w"> </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">name</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="nb">close</span><span class="p">(</span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="yu-fang-ke-hu-duan-yan-chi-ying-xiang"><a class="toclink" href="#yu-fang-ke-hu-duan-yan-chi-ying-xiang">预防客户端延迟影响</a></h4>
<p>最后还有一个问题，就是客户端可能会卡或者延迟，但是客户端的问题不能影响到服务器的正常运行。不过我没法实现一个这样的有延迟的客户端，默认操作系统应该就已经非常友好的帮我们处理掉了，把从网络上接收到的数据暂存在缓冲区里（<em>对于TCP连接还有乱序重组和超时重传，这些我们都不需要关心了</em>），等待程序去读取。代码里接收的操作应该是直接从缓冲区读取，这时服务的已经发送完毕了。所以现在只能照着下面的思路写了：  </p>
<blockquote>
<p>任何客户程序读取数据的时间很长最终会造成所有的客户卡住。修改广播器，使它满足如果一个向客户写入的通道没有准备好接受它，那么跳过这条消息。还可以给每一个向客户发送消息的通道增加缓冲，这样大多数的消息不会丢弃；广播器在这个通道上应该使用非阻塞的发送方式。  </p>
</blockquote>
<p>客户端处理函数中创建的发送消息的通道改用有缓冲区的通道：</p>
<div class="highlight"><pre><span></span><code><span class="c1">// 客户端处理函数</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"> </span><span class="c1">// 退出时关闭客户端连接，现在有分支了，并且可能会提前退出</span><span class="w"></span>

<span class="w">    </span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientRegiste</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注册获取用户名</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">ok</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 用户名未注册成功</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\r\nName registe failed...&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>

<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="mi">10</span><span class="p">)</span><span class="w"> </span><span class="c1">// 有缓冲区，对外发送客户消息的通道</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="c1">// 省略后面的代码</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<p>然后广播器的 select 对应的 messages 通道的分支，改成非阻塞的方式：</p>
<div class="highlight"><pre><span></span><code><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="k">case</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">messages</span><span class="p">:</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 把所有接收的消息广播给所有的客户</span><span class="w"></span>
<span class="w">    </span><span class="c1">// 发送消息通道</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">name</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">msg</span><span class="p">:</span><span class="w"></span>
<span class="w">        </span><span class="k">default</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintf</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stderr</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;send message failed: %s: %s\n&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">name</span><span class="p">,</span><span class="w"> </span><span class="nx">msg</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="c1">// 其他分支略过</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>

<h4 id="wan-zheng-dai-ma"><a class="toclink" href="#wan-zheng-dai-ma">完整代码</a></h4>
<p>下面是聊天服务器最后完整的代码。这里的改变还包括了上一节最后提到的注册用户名时的输入的超时。已经两次用到了输入超时，分别在 handleConn 和 clientRegiste 中，这里也就把这部分代码单独写了一个函数 inputWithTimeout。<br>
完整代码如下：</p>
<div class="highlight"><pre><span></span><code><span class="kn">package</span><span class="w"> </span><span class="nx">main</span><span class="w"></span>

<span class="kn">import</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;bufio&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;fmt&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;log&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;net&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;os&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;strings&quot;</span><span class="w"></span>
<span class="w">    </span><span class="s">&quot;time&quot;</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">listener</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Listen</span><span class="p">(</span><span class="s">&quot;tcp&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;:8000&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">log</span><span class="p">.</span><span class="nx">Fatal</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">listener</span><span class="p">.</span><span class="nx">Accept</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">log</span><span class="p">.</span><span class="nx">Print</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">continue</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">go</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="c1">// 广播器</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">client</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="c1">// 对外发送消息的通道</span><span class="w"></span>
<span class="kd">type</span><span class="w"> </span><span class="nx">clientInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="nx">client</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="p">(</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">leaving</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有接受的客户消息</span><span class="w"></span>
<span class="p">)</span><span class="w"></span>

<span class="kd">type</span><span class="w"> </span><span class="nx">registeInfo</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">name</span><span class="w"> </span><span class="kt">string</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w">   </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kt">bool</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">var</span><span class="w"> </span><span class="nx">register</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="nx">registeInfo</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注册用户名的通道</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">broadcaster</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">clients</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="nx">client</span><span class="p">)</span><span class="w"> </span><span class="c1">// 所有连接的客户端集合</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">messages</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 把所有接收的消息广播给所有的客户</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 发送消息通道</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">name</span><span class="p">,</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="k">case</span><span class="w"> </span><span class="nx">cli</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">msg</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="k">default</span><span class="p">:</span><span class="w"></span>
<span class="w">                    </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintf</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Stderr</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;send message failed: %s: %s\n&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">name</span><span class="p">,</span><span class="w"> </span><span class="nx">msg</span><span class="p">)</span><span class="w"></span>
<span class="w">                </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">user</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">register</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 先判断新用户名是否有重复</span><span class="w"></span>
<span class="w">            </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clients</span><span class="p">[</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="p">]</span><span class="w"></span>
<span class="w">            </span><span class="nx">user</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="p">!</span><span class="nx">ok</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cliSt</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">entering</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="c1">// 在每一个新用户到来的时候，通知当前存在的用户</span><span class="w"></span>
<span class="w">            </span><span class="kd">var</span><span class="w"> </span><span class="nx">users</span><span class="w"> </span><span class="p">[]</span><span class="kt">string</span><span class="w"></span>
<span class="w">            </span><span class="k">for</span><span class="w"> </span><span class="nx">user</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">clients</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">users</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nb">append</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="nx">user</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">users</span><span class="p">)</span><span class="w"> </span><span class="p">&gt;</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Sprintf</span><span class="p">(</span><span class="s">&quot;Other users in room: %s&quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">strings</span><span class="p">.</span><span class="nx">Join</span><span class="p">(</span><span class="nx">users</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;; &quot;</span><span class="p">))</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are the only user in this room.&quot;</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>

<span class="w">            </span><span class="nx">clients</span><span class="p">[</span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">name</span><span class="p">]</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="w"></span>
<span class="w">        </span><span class="k">case</span><span class="w"> </span><span class="nx">cliSt</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">leaving</span><span class="p">:</span><span class="w"></span>
<span class="w">            </span><span class="nb">delete</span><span class="p">(</span><span class="nx">clients</span><span class="p">,</span><span class="w"> </span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">name</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="nb">close</span><span class="p">(</span><span class="nx">cliSt</span><span class="p">.</span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="c1">// 客户端处理函数</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">handleConn</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">defer</span><span class="w"> </span><span class="nx">conn</span><span class="p">.</span><span class="nx">Close</span><span class="p">()</span><span class="w"> </span><span class="c1">// 退出时关闭客户端连接，现在有分支了，并且可能会提前退出</span><span class="w"></span>

<span class="w">    </span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientRegiste</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注册获取用户名</span><span class="w"></span>
<span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">ok</span><span class="w"> </span><span class="p">{</span><span class="w">                       </span><span class="c1">// 用户名未注册成功</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;\r\nName registe failed...&quot;</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">return</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>

<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="mi">10</span><span class="p">)</span><span class="w"> </span><span class="c1">// 有缓冲区，对外发送客户消息的通道</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="nx">cli</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">clientInfo</span><span class="p">{</span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">}</span><span class="w">       </span><span class="c1">// 打包好用户名和通道</span><span class="w"></span>
<span class="w">    </span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="s">&quot;You are &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">who</span><span class="w">           </span><span class="c1">// 这条单发给自己</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has arrived&quot;</span><span class="w"> </span><span class="c1">// 现在这条广播自己也能收到</span><span class="w"></span>
<span class="w">    </span><span class="nx">entering</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">cli</span><span class="w"></span>

<span class="w">    </span><span class="nx">inputFunc</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="kd">func</span><span class="p">(</span><span class="nx">sig</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="nx">sig</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w">                              </span><span class="c1">// 向 sig 发送信号，会重新开始计时</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">strings</span><span class="p">.</span><span class="nx">TrimSpace</span><span class="p">(</span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()))</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 禁止发送纯空白字符</span><span class="w"></span>
<span class="w">                </span><span class="k">continue</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot;: &quot;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="c1">// 注意，忽略input.Err()中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">inputWithTimeout</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="mi">300</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">,</span><span class="w"> </span><span class="nx">inputFunc</span><span class="p">)</span><span class="w"></span>

<span class="w">    </span><span class="nx">leaving</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">cli</span><span class="w"></span>
<span class="w">    </span><span class="nx">messages</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">who</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&quot; has left&quot;</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="kd">func</span><span class="w"> </span><span class="nx">clientWriter</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="w"> </span><span class="o">&lt;-</span><span class="kd">chan</span><span class="w"> </span><span class="kt">string</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">msg</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">ch</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="c1">// windows 需要 \r 了正常显示</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintln</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="nx">msg</span><span class="o">+</span><span class="s">&quot;\r&quot;</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意，忽略网络层面的错误</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="c1">// 注册用户名</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">clientRegiste</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nx">who</span><span class="w"> </span><span class="kt">string</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="kt">bool</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">inputFunc</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="kd">func</span><span class="p">(</span><span class="nx">sig</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">input</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">bufio</span><span class="p">.</span><span class="nx">NewScanner</span><span class="p">(</span><span class="nx">conn</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">ch</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kt">bool</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprint</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;input nickname: &quot;</span><span class="p">)</span><span class="w"> </span><span class="c1">// 注意，忽略网络层面的错误</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Scan</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="nb">len</span><span class="p">(</span><span class="nx">strings</span><span class="p">.</span><span class="nx">TrimSpace</span><span class="p">(</span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()))</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// 禁止发送纯空白字符</span><span class="w"></span>
<span class="w">                </span><span class="k">continue</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="nx">who</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">input</span><span class="p">.</span><span class="nx">Text</span><span class="p">()</span><span class="w"></span>
<span class="w">            </span><span class="nx">register</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="nx">registeInfo</span><span class="p">{</span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ch</span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="k">if</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">ch</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">                </span><span class="nx">ok</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="kc">true</span><span class="w"></span>
<span class="w">                </span><span class="k">break</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">            </span><span class="nx">fmt</span><span class="p">.</span><span class="nx">Fprintf</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;name %q is existed\r\ntry other name: &quot;</span><span class="p">,</span><span class="w"> </span><span class="nx">who</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="c1">// 注意，忽略input.Err()中可能的错误</span><span class="w"></span>
<span class="w">    </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="nx">inputWithTimeout</span><span class="p">(</span><span class="nx">conn</span><span class="p">,</span><span class="w"> </span><span class="mi">15</span><span class="o">*</span><span class="nx">time</span><span class="p">.</span><span class="nx">Second</span><span class="p">,</span><span class="w"> </span><span class="nx">inputFunc</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="nx">who</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>

<span class="c1">// 为 input.Scan 封装超时退出的功能</span><span class="w"></span>
<span class="kd">func</span><span class="w"> </span><span class="nx">inputWithTimeout</span><span class="p">(</span><span class="nx">conn</span><span class="w"> </span><span class="nx">net</span><span class="p">.</span><span class="nx">Conn</span><span class="p">,</span><span class="w"> </span><span class="nx">timeout</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">Duration</span><span class="p">,</span><span class="w"> </span><span class="nx">input</span><span class="w"> </span><span class="kd">func</span><span class="p">(</span><span class="nx">sig</span><span class="w"> </span><span class="kd">chan</span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}))</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">    </span><span class="nx">done</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{},</span><span class="w"> </span><span class="mi">2</span><span class="p">)</span><span class="w"></span>
<span class="w">    </span><span class="nx">inputSignal</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">(</span><span class="kd">chan</span><span class="w"> </span><span class="kd">struct</span><span class="p">{})</span><span class="w"></span>
<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">timer</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">time</span><span class="p">.</span><span class="nx">NewTimer</span><span class="p">(</span><span class="nx">timeout</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="k">for</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">select</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">inputSignal</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="nx">timer</span><span class="p">.</span><span class="nx">Reset</span><span class="p">(</span><span class="nx">timeout</span><span class="p">)</span><span class="w"></span>
<span class="w">            </span><span class="k">case</span><span class="w"> </span><span class="o">&lt;-</span><span class="nx">timer</span><span class="p">.</span><span class="nx">C</span><span class="p">:</span><span class="w"></span>
<span class="w">                </span><span class="c1">// 超时，断开连接</span><span class="w"></span>
<span class="w">                </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">                </span><span class="k">return</span><span class="w"></span>
<span class="w">            </span><span class="p">}</span><span class="w"></span>
<span class="w">        </span><span class="p">}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="k">go</span><span class="w"> </span><span class="kd">func</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"></span>
<span class="w">        </span><span class="nx">input</span><span class="p">(</span><span class="nx">inputSignal</span><span class="p">)</span><span class="w"></span>
<span class="w">        </span><span class="nx">done</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="kd">struct</span><span class="p">{}{}</span><span class="w"></span>
<span class="w">    </span><span class="p">}()</span><span class="w"></span>

<span class="w">    </span><span class="o">&lt;-</span><span class="nx">done</span><span class="w"></span>
<span class="p">}</span><span class="w"></span>
</code></pre></div>
      </div>
      <div class="back-to-top">
        <a href="/">HOME</a>
        <a href="#top">TOP</a>
      </div>
    </article>
  </div>
<!-- end article -->
<!-- 页面往下滚动一段之后才会显示TOC -->
<script>
  window.onscroll = function() {
    var tocbox = document.getElementsByClassName('toc')[0];
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    var osWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    // console.log(osTop)
    if (osTop>300 && osWidth>865) {
      tocbox.style.display = "block"
    }
    if (osTop<300 || osWidth<865) {
      tocbox.style.display = "none"
    }
  }
</script>
                <footer>
                    <div class="icons">
                    </div>
                    <span id="busuanzi_container_page_pv" style="padding: 10px">本文阅读量<span id="busuanzi_value_page_pv"></span>次</span>
                    <span id="busuanzi_container_site_pv" style="padding: 10px">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
                    <span id="busuanzi_container_site_uv" style="padding: 10px">本站总访客数<span id="busuanzi_value_site_uv"></span>人</span>
                    <p>© <script>document.write(moment().format('YYYY'));</script> 749B</p>
                </footer>
        </div>
</body>
</html>